const Koa = require("koa");

const koaBody = require("koa-body");
const path = require("path");
// 静态资源部署
const static = require("koa-static");
const views = require('koa-views')

// 静态资源目录对于相对入口文件index.js的路径
// const convert = require("koa-convert");
const staticPath = "./public";

const bodyParser = require("koa-bodyparser");
const cookieParser = require("cookie-parser");
const Jwt = require("./untils/jwt");

const controller = require("./controller");

const app = new Koa();

require("./plugins/db")();

app.use(views('./',{
  extension:'ejs'
}))

// 由于koa-static目前不支持koa2
// 所以只能用koa-convert封装一下
// app.use(convert(static(path.join(__dirname, staticPath))));
app.use(static(path.join(__dirname, staticPath)));

// log request URL:
app.use(async (ctx, next) => {
  const match = new RegExp("/public");
  // 我这里知识把登陆和注册请求去掉了，其他的多有请求都需要进行token校验
  if (
    ctx.request.url !== "/login" &&
    ctx.request.url !== "/public/apidoc/index.html" &&
    ctx.request.url !== "/" &&
    ctx.request.url !== "/favicon.ico" &&
    ctx.request.url !== "/apidoc/index.html" &&
    ctx.request.url !== "/manage/img/upload" &&
    !match.test(ctx.request.url)
  ) {
    let token = ctx.request.headers.token;
    console.log(token);
    const jwt = new Jwt(token);
    let result = jwt.verifyToken();
    // 如果考验通过就next，否则就返回登陆信息不正确
    if (result == "err") {
      console.log(result);
      ctx.body = { code: 403, message: "登录已过期,请重新登录" };
    } else {
      await next();
    }
  } else {
    await next();
  }
  // await next();
});

app.use(
  koaBody({
    // 支持文件格式
    multipart: true,
    formidable: {
      // 上传目录
      uploadDir: path.join(__dirname, "public/upload"),
      // 保留文件扩展名
      keepExtensions: true,
    },
  })
);

// parse request body:
app.use(bodyParser());

// add controllers:
app.use(controller());

app.listen(3001);
console.log("app started at port 3001...");
